<template>
  <div class="shop-form">
    <el-card class="form-card">
      <template #header>
        <div class="card-header">
          <span>{{ isEdit ? '编辑店铺' : '添加店铺' }}</span>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
        class="form"
      >
        <!-- 基本信息 -->
        <el-divider content-position="left">基本信息</el-divider>
        <el-form-item label="店铺名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入店铺名称" />
        </el-form-item>

        <el-form-item label="店铺Logo" prop="logo">
          <el-upload
            class="logo-uploader"
            :action="null"
            :http-request="uploadLogo"
            :show-file-list="false"
            :before-upload="beforeLogoUpload"
          >
            <img v-if="formData.logo" :src="formData.logo" class="logo" />
            <el-icon v-else class="logo-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">建议尺寸：200x200px，支持jpg、png格式</div>
        </el-form-item>

        <el-form-item label="店主姓名" prop="owner">
          <el-input v-model="formData.owner" placeholder="请输入店主姓名" />
        </el-form-item>

        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入联系电话" />
        </el-form-item>

        <!-- 营业信息 -->
        <el-divider content-position="left">营业信息</el-divider>
        <el-form-item label="营业时间" prop="businessHours">
          <el-time-picker
            v-model="formData.openTime"
            placeholder="开始时间"
            format="HH:mm"
            value-format="HH:mm"
            style="width: 180px"
          />
          <span class="separator">-</span>
          <el-time-picker
            v-model="formData.closeTime"
            placeholder="结束时间"
            format="HH:mm"
            value-format="HH:mm"
            style="width: 180px"
          />
        </el-form-item>

        <el-form-item label="店铺状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :value="1">营业中</el-radio>
            <el-radio :value="0">已关闭</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 地址信息 -->
        <el-divider content-position="left">地址信息</el-divider>
        <el-form-item label="所在地区" prop="region">
          <el-cascader
            v-model="formData.region"
            :options="regionOptions"
            :props="{ expandTrigger: 'hover' }"
            placeholder="请选择所在地区"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="详细地址" prop="address">
          <el-input
            v-model="formData.address"
            type="textarea"
            :rows="2"
            placeholder="请输入详细地址"
          />
        </el-form-item>

        <!-- 店铺简介 -->
        <el-divider content-position="left">店铺简介</el-divider>
        <el-form-item label="店铺简介" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="4"
            placeholder="请输入店铺简介"
          />
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            {{ isEdit ? '保存修改' : '创建店铺' }}
          </el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElLoading } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import service from '@/utils/request'
import { addShop, updateShop, getShopDetail } from '@/api/shop'
import { getCookieValue } from '@/utils/request'
import { useAdminStore } from '@/stores/modules/admin' // 导入管理员store

// 导入地区数据和转换函数
import regionData from '/public/data/pca-code.json'
import { transformRegionData } from '@/utils/region'

const route = useRoute()
const router = useRouter()
const formRef = ref(null)
const submitting = ref(false)

// 判断是否为编辑模式
const isEdit = computed(() => !!route.params.id)

// 表单数据
const formData = ref({
  name: '',
  logo: '',
  owner: '',
  phone: '',
  openTime: '',
  closeTime: '',
  status: 1,
  region: [],
  address: '',
  description: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入店铺名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  logo: [
    { required: true, message: '请上传店铺Logo', trigger: 'change' }
  ],
  owner: [
    { required: true, message: '请输入店主姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  openTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  closeTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ],
  region: [
    { required: true, message: '请选择所在地区', trigger: 'change' }
  ],
  address: [
    { required: true, message: '请输入详细地址', trigger: 'blur' }
  ]
}

// 地区数据 - 转换为级联选择器格式
const regionOptions = ref(transformRegionData(regionData))

// Logo上传前的验证
const beforeLogoUpload = (file) => {
  const isImage = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传JPG/PNG格式的图片！')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB！')
    return false
  }
  return true
}

// 上传Logo
const uploadLogo = async (options) => {
  const { file, onSuccess, onError } = options
  try {
    // 显示加载状态
    const loadingInstance = ElLoading.service({
      text: '图片上传中...',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    
    // 获取管理员store
    const adminStore = useAdminStore()
    
    // 使用Promise包装XMLHttpRequest
    const response = await new Promise((resolve, reject) => {
      const formData = new FormData()
      formData.append('file', file)
      
      const xhr = new XMLHttpRequest()
      // 使用管理员上传接口
      xhr.open('POST', import.meta.env.VITE_API_BASE_URL + '/files/jiang/upload', true)
      
      // 使用管理员token
      if (adminStore.accessToken) {
        xhr.setRequestHeader('Authorization', `Bearer ${adminStore.accessToken}`)
      } else {
        // 如果没有管理员token，尝试从localStorage获取
        const token = localStorage.getItem('admin_token')
        if (token) {
          xhr.setRequestHeader('Authorization', `Bearer ${token}`)
        }
      }
      
      xhr.onload = function() {
        if (xhr.status >= 200 && xhr.status < 300) {
          try {
            const response = JSON.parse(xhr.responseText)
            resolve(response.data)
          } catch (e) {
            resolve(xhr.responseText)
          }
        } else {
          reject(new Error(`上传失败：${xhr.status} ${xhr.statusText}`))
        }
      }
      
      xhr.onerror = function() {
        reject(new Error('网络错误，上传失败'))
      }
      
      xhr.send(formData)
    })
    
    // 关闭加载状态
    loadingInstance.close()
    
    // 处理响应
    let logoUrl = ''
    
    if (response && typeof response === 'string') {
      logoUrl = response
    } else if (response && response.data) {
      logoUrl = typeof response.data === 'string' ? response.data : response.data.url || response.data
    } else {
      logoUrl = response
    }
    
    // 检查URL是否有效
    if (!logoUrl) {
      throw new Error('上传成功但未获取到有效的图片URL')
    }
    
    // 更新Logo URL
    formData.value.logo = logoUrl
    
    // 如果onSuccess回调存在则调用
    if (onSuccess) {
      onSuccess({ data: logoUrl })
    }
    
    ElMessage.success('Logo上传成功')
  } catch (error) {
    // 关闭可能存在的加载状态
    try {
      ElLoading.service().close()
    } catch (e) {
      // 忽略关闭加载状态时的错误
    }
    
    console.error('Logo上传失败:', error)
    
    // 处理特定错误
    let errorMessage = '上传失败'
    
    if (error.response) {
      const status = error.response.status
      
      if (status === 401 || status === 403) {
        errorMessage = '权限不足或未登录，请重新登录后再试'
      } else if (status === 413) {
        errorMessage = '文件太大，请选择小于2MB的图片'
      } else {
        errorMessage = `服务器错误 (${status}): ${error.response.data?.message || '未知错误'}`
      }
    } else {
      errorMessage = error.message || '网络连接问题，请稍后再试'
    }
    
    // 显示错误消息
    ElMessage.error(errorMessage)
    
    // 调用错误回调
    if (onError) {
      onError(error)
    }
  }
}

// 获取店铺详情
const getShopInfo = async (id) => {
  try {
    const data = await getShopDetail(id)
    console.log('获取到的店铺详情:', data)
    // 根据后端返回的数据结构适配表单数据
    formData.value = {
      id: data.id, // 确保id字段被正确设置
      name: data.name,
      logo: data.image,
      owner: data.userId, // 可能需要额外获取店主信息
      phone: data.phone,
      address: data.address,
      description: data.description || '',
      status: data.status,
      // 解析营业时间
      openTime: data.openHours ? data.openHours.split('-')[0] : '',
      closeTime: data.openHours ? data.openHours.split('-')[1] : '',
      // 解析地区 - 从area字符串解析为数组
      region: data.area ? parseRegion(data.area) : [],
      // 其他字段
      email: data.email
    }
  } catch (error) {
    console.error('获取店铺详情失败：', error)
    ElMessage.error('获取店铺详情失败')
  }
}

// 解析地区字符串为级联数组
const parseRegion = (areaStr) => {
  // 这里需要根据实际情况解析，例如"北京市海淀区"可能需要拆分为["北京市", "海淀区"]
  // 简单实现，实际可能需要更复杂的匹配逻辑
  const provinces = regionOptions.value.map(p => p.label)
  let result = []
  
  for (const province of provinces) {
    if (areaStr.includes(province)) {
      const provinceObj = regionOptions.value.find(p => p.label === province)
      result.push(provinceObj.value)
      
      if (provinceObj.children) {
        for (const city of provinceObj.children) {
          if (areaStr.includes(city.label)) {
            result.push(city.value)
            
            if (city.children) {
              for (const district of city.children) {
                if (areaStr.includes(district.label)) {
                  result.push(district.value)
                  break
                }
              }
            }
            break
          }
        }
      }
      break
    }
  }
  
  return result
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  try {
    await formRef.value.validate()
    submitting.value = true
    
    // 处理地区数据
    let areaText = ''
    if (formData.value.region && formData.value.region.length > 0) {
      const [provinceCode, cityCode, districtCode] = formData.value.region
      
      // 获取省市区的文字描述
      const provinceText = regionOptions.value.find(p => p.value === provinceCode)?.label || ''
      const cityText = regionOptions.value
        .find(p => p.value === provinceCode)
        ?.children?.find(c => c.value === cityCode)?.label || ''
      const districtText = regionOptions.value
        .find(p => p.value === provinceCode)
        ?.children?.find(c => c.value === cityCode)
        ?.children?.find(d => d.value === districtCode)?.label || ''
      
      areaText = [provinceText, cityText, districtText].filter(Boolean).join('')
    }
    
    // 确保ID是数字类型
    const shopId = isEdit.value ? parseInt(route.params.id) : undefined
    
    const shop = {
      id: shopId, // 使用转换后的数字类型ID
      name: formData.value.name,
      image: formData.value.logo,
      userId: formData.value.owner,
      area: areaText, // 使用处理后的地区文本
      address: formData.value.address,
      phone: formData.value.phone,
      email: formData.value.email,
      openHours: formData.value.openTime && formData.value.closeTime ? `${formData.value.openTime}-${formData.value.closeTime}` : '',
      status: formData.value.status,
      description: formData.value.description
    }
    
    console.log('提交的店铺数据:', shop)
    
    if (isEdit.value) {
      await updateShop(shop)
      ElMessage.success('修改成功')
    } else {
      await addShop(shop)
      ElMessage.success('创建成功')
    }
    router.push('/jiang/shop')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('提交失败：', error)
      ElMessage.error('提交失败，请检查表单')
    }
  } finally {
    submitting.value = false
  }
}

// 取消
const handleCancel = () => {
  router.back()
}

onMounted(() => {
  if (isEdit.value) {
    // 确保使用数字类型的ID
    const shopId = parseInt(route.params.id)
    getShopInfo(shopId)
  }
})
</script>

<style lang="scss" scoped>
.shop-form {
  .form-card {
    .card-header {
      font-size: 16px;
      font-weight: 500;
    }

    .form {
      max-width: 800px;
      margin: 0 auto;
    }
  }

  .logo-uploader {
    :deep(.el-upload) {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);

      &:hover {
        border-color: var(--el-color-primary);
      }
    }

    .logo-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 100px;
      height: 100px;
      text-align: center;
      line-height: 100px;
    }

    .logo {
      width: 100px;
      height: 100px;
      display: block;
      object-fit: cover;
    }
  }

  .upload-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 8px;
  }

  .separator {
    margin: 0 8px;
    color: #909399;
  }

  :deep(.el-divider__text) {
    font-size: 14px;
    font-weight: 500;
  }
}
</style>
